<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace App\Model;
use App\Entity\ApiMoneyLog;
use App\Base\BaseModel;
use App\Setting\ApiMoneyLogSetting;

class ApiMoneyLogModel extends BaseModel{

    /*
     * 列表基本设置【通用模块必须开发】
     */
    public function listSettingDefault()
    {
        $settings = new ApiMoneyLogSetting($this->getDoctrine());
        return $settings->listConfig();
    }

    /*
     * 为后台获取所有文章分类【通用模块必须开发】
     */
    /**
     * @param array $params $param[textKey]=textKey , $param[conditions][table][field][eq|gt|lt...]=value , $param[orderBy][table][field]=DESC|ASC
     * @param int $offset
     * @param int $perPage
     * @return array
     */
    public function getAdminLists($params ,$offset = 0 , $perPage = 10)
    {
        $qb = $this->getQueryFromParam($params);
        $lists = $this->getAllResult($qb,$offset,$perPage);
        $total = $this->countAllResult($qb);

        return array(
            "total" => $total ? $total : 0,
            "data"  => $lists
        );
    }

    /**
     * @return \Doctrine\Common\Persistence\ObjectRepository|\Doctrine\ORM\EntityRepository
     */
    public function getRep()
    {
        $settings = new ApiMoneyLogSetting($this->getDoctrine());
        return $this->em->getRepository($settings->bundleName.":".$settings->entityName);
    }

    /**
     * @return ApiMoneyLog[]
     */
    public function getAll()
    {
        return $this->getRep()->findBy(array(),array("id"=>"DESC"));
    }

    /**
     * @param $id
     * @return null|object|ApiMoneyLog
     */
    public function getById($id)
    {
        return $this->getRep()->find($id);
    }

    /**
     * @return array
     */
    public function getAllArray()
    {
        $data = $this->getAll();
        $re = [];
        foreach ($data as $one) {
            $re[] = $this->toArray($one);
        }
        return $re;
    }

    /**
     * @param $id
     * @return array
     */
    public function getByIdArray($id)
    {
        $en = $this->getById($id);
        return $en?$this->toArray($en):[];
    }


    /**
     * @param $key
     * @param $val
     * @return ApiMoneyLog
     */
    public function getByKV($key,$val)
    {
        $qb = $this->createDql();
        $qb->select("A")->from("App:ApiMoneyLog","A");
        $qb->where("A.$key = $val");
        $query = $qb->getQuery();
        $data = $query->execute();
        if ($data) {
            return $data[0];
        }else{
            return [];
        }
    }

    /**
     * @param $key
     * @param $val
     * @return ApiMoneyLog[]
     */
    public function getArrayByKV($key,$val)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("A.*")->from("ApiMoneyLog","A");
        $qb->where("A.$key = $val")->orderBy("id","DESC");
        $data = $qb->execute()->fetchAll();
        return $data;
    }

    /**
     * @param $project
     * @param $userId
     * @param $moneyType
     * @param $type
     * @param $money
     * @param string $tips
     * @return bool|string
     */
    public function add($project , $userId , $moneyType , $type , $money  , $tips = "")
    {
        if (substr($type,0,1) == 1 && $money <= 0) {
            return "进项资金不能为负数";
        }
        if (substr($type,0,1) == 2 && $money >= 0) {
            return "销项资金不能为正数";
        }
        $this->myEm()->beginTransaction();
        try {
            //添加资金记录
            $ApiMoneyLog = new ApiMoneyLog();
            $ApiMoneyLog->setProjectId($project)
                ->setMoneyType($moneyType)
                ->setType($type)
                ->setMoney($money)
                ->setTips($tips)
                ->setUserId($userId)
                ->setAddtime(time());
            $this->em->persist($ApiMoneyLog);$this->em->flush();
            //修改持有金额
            $ApiMoneyModel = new ApiMoneyModel($this->getDoctrine());
            $err = $ApiMoneyModel->addMoney($project , $userId , $moneyType ,$money);
            if ($err) {
                return $err;
            }
            //修改资金统计数据
            $ApiUserStaticModel = new ApiUserStaticModel($this->getDoctrine());
            $ApiUserStaticModel->addMoney($project , $userId , $moneyType , $type ,$money);
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }

        $this->myEm()->commit();
        return false;
    }
    /**
     * @param $project
     * @param $userId
     * @param $moneyType
     * @param $type
     * @param $money
     * @param string $tips
     * @return bool|string
     */
    public function addStatic($project , $userId , $moneyType , $type , $money  , $tips = "")
    {
        $this->myEm()->beginTransaction();
        try {
            //添加资金记录
            $ApiMoneyLog = new ApiMoneyLog();
            $ApiMoneyLog->setProjectId($project)
                ->setMoneyType($moneyType)
                ->setType($type)
                ->setMoney($money)
                ->setTips($tips)
                ->setUserId($userId)
                ->setAddtime(time());
            $this->em->persist($ApiMoneyLog);$this->em->flush();
            //修改资金统计数据
            $ApiUserStaticModel = new ApiUserStaticModel($this->getDoctrine());
            $ApiUserStaticModel->addMoney($project , $userId , $moneyType , $type ,$money);
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }

        $this->myEm()->commit();
        return false;
    }

    /**
     * @param $project
     * @param $userId
     * @param $moneyType
     * @param $type
     * @return bool|ApiMoneyLog
     */
    public function getLastLog($project , $userId , $moneyType , $type)
    {
        $data = $this->getRep()->findBy(array(
            "projectId"=>$project,
            "userId"   =>$userId,
            "moneyType"=>$moneyType,
            "type"=>$type
        ),array("addtime"=>"DESC"),1,0);
        if ($data) {
            return $data[0];
        }else{
            return false;
        }
    }


    public function getTermsList($project , $userId , $moneyType , $type , $startTime , $endTime ,$page , $limit)
    {
        $offset = $page * $limit;
        $sql = "Select A.*
        From api_money_log A
        Where A.project_id = $project
        And A.money_type = $moneyType
        And A.type = $type
        And A.addtime >= '$startTime'
        And A.addtime < '$endTime'
        And A.user_id = $userId
        ORDER BY A.addtime DESC
        LIMIT $limit OFFSET $offset
        ";
        $data = $this->excSql($sql);
        return $data;
    }

    public function getTermsSum($project , $userId , $moneyType , $type , $startTime , $endTime ,$page , $limit)
    {
        $offset = $page * $limit;
        $sql = "Select sum(A.money) as total
        From api_money_log A
        Where A.project_id = $project
        And A.money_type = $moneyType
        And A.type = $type
        And A.addtime >= '$startTime'
        And A.addtime < '$endTime'
        And A.user_id = $userId
        GROUP BY A.user_id
        ORDER BY A.addtime DESC
        LIMIT $limit OFFSET $offset
        ";
        $data = $this->excSql($sql);
        if ($data) {
            return $data[0]["total"];
        } else{
            return 0;
        }
    }
}